package com.faiz;

import com.faiz.algorithm.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
//        if (root == null) {
//            return "[]";
//        }
//        Queue<TreeNode> queue = new LinkedList<>();
//        StringBuilder stringBuilder = new StringBuilder("[");
//        queue.offer(root);
//        while (!queue.isEmpty()) {
//            TreeNode node = queue.poll();
//            if (node != null) {
//                stringBuilder.append(node.val + ",");
//                queue.offer(node.left);
//                queue.offer(node.right);
//            } else {
//                stringBuilder.append("null,");
//            }
//
//        }
//        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
//        stringBuilder.append("]");
//        return stringBuilder.toString();
        if (root == null) return "[]";
        StringBuilder res = new StringBuilder("[");
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node != null) {
                res.append(node.val + ",");
                queue.add(node.left);
                queue.add(node.right);
            } else res.append("null,");
        }
        res.deleteCharAt(res.length() - 1);
        res.append("]");
        return res.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if (data.equals("[]")) {
            return null;
        }
        String[] vals = data.substring(1, data.length() - 1).split(",");
        return stringArray2Tree(vals, 0);
    }

    public TreeNode stringArray2Tree(String[] array, int index) {
        TreeNode root = null;
        if (index < array.length) {
            String value = array[index];
            if (!value.equals("null")) {
                root = new TreeNode(Integer.parseInt(value));
                root.left = stringArray2Tree(array, 2 * index + 1);
                root.right = stringArray2Tree(array, 2 * index + 2);
            }
        }
        return root;
    }
}